package com.norra.client

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.preference.PreferenceManager
import com.norra.base.api.BaseApp
import com.norra.base.api.WebService
import com.norra.base.utils.ContextHolder
import com.norra.client.ui.LoginActivity

class App : BaseApp() {

    private var token: String? = null

    val mainHandler = Handler(Looper.getMainLooper())

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        instance = this
        ContextHolder.initContext(this)
        this.token = PreferenceManager.getDefaultSharedPreferences(this).getString("user_token", null)
        if (token != null) {
            WebService.setToken(token!!)
        }
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onUserTokenExpired() {
        clearUserToken()
        val intent = Intent(this, LoginActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)
    }

    fun saveUserToken(token: String) {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("user_token", token).apply()
        this.token = token
        WebService.setToken(token)
    }

    fun clearUserToken() {
        PreferenceManager.getDefaultSharedPreferences(this).edit().remove("user_token").apply()
        this.token = null
        WebService.setToken(null)
    }

    public fun isLogin(): Boolean {
        return token != null
    }


    companion object {
        lateinit var instance: App
        fun get(): App {
            return instance
        }
    }
}